package com.ruoyi.meiyijia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.meiyijia.entity.FileMeiyijiaInventory;
import com.ruoyi.meiyijia.mapper.FileMeiyijiaInventoryMapper;
import com.ruoyi.meiyijia.service.FileMeiyijiaInventoryService;
import com.ruoyi.common.utils.file.parsing.excel.ExcelParsingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * @author: TheRaging
 * @date: 2023年05月18日 09:04:00
 * @description:
 */
@Service
@Slf4j
public class FileMeiyijiaInventoryServiceImpl implements FileMeiyijiaInventoryService {
    /**
     * 导入文件的批量插入的接口
     *
     * @param inputStream
     */

    @Autowired
    private ExcelParsingUtil<FileMeiyijiaInventory> excelParsingUtil;
    
    @Resource
    private FileMeiyijiaInventoryMapper fileMeiyijiaInventoryMapper;
    
    
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(MultipartFile file) {
        String filePath = file.getOriginalFilename();
    
        InputStream fis = null;
        try {
            fis = file.getInputStream();
            Workbook workbook = null;
            if (filePath.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (filePath.endsWith(".xls") || filePath.endsWith(".et")) {
                workbook = new HSSFWorkbook(fis);
            }
        
            fis.close();
  
            // 获取第一个sheet表，也可使用sheet表名获取
            Sheet sheet = workbook.getSheetAt(0);
            LocalDateTime dateTime = LocalDateTime.now();
            /**
             * 生成唯一标识
             */
            StringBuffer str = new StringBuffer();
            str.append(dateTime.getYear());
            str.append(dateTime.getMonthValue()<10?"0"+dateTime.getMonthValue():dateTime.getMonthValue());
            str.append(dateTime.getDayOfMonth()<10?"0"+dateTime.getDayOfMonth():dateTime.getDayOfMonth());
            Random r = new Random();
            str.append(r.nextInt());
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/M/d H:m:s");
            List<FileMeiyijiaInventory> list = excelParsingUtil.getSheetByIndex(FileMeiyijiaInventory.class,sheet,(val, i,item)->{
                switch (i){
                    case 0:
                        item.setBigType(val);
                        break;
                    case 1:
                        item.setType(val);
                        break;
                    case 2:
                       // System.out.println("第二列跳过-----------");
                        break;
                    case 3:
                        item.setCode(val);
                        break;
                    case 4:
                        item.setBarCode(val);
                        break;
                    case 5:
                        item.setNameSpecification(val);
                        break;
                    case 6:
                        item.setUnit(val);
                        break;
                    case 7:
                        item.setWholesalePrice(val);
                        break;
                    case 8:
                        item.setMsrpPrice(val);
                        break;
                    case 9:
                        item.setRetailPrive(val);
                        break;
                    case 10:
                        item.setCount(val);
                        break;
                    case 11:
                        item.setQualityTerm(val);
                        break;
                    case 12:
                        item.setWarehousingTime(LocalDateTime.parse(val,df));
                        break;
                }
                /**
                 * 设置批次值
                 */
                return item;
            },item->{
                item.setCrtTime(dateTime);
                item.setId(str.toString());
            });
            
            /**
             * 批量插入数据库
             */
            int count = fileMeiyijiaInventoryMapper.insertbatch(list);
            if(count!=list.size()){
                throw new Exception("库存数据入库失败！");
            }
            
        }catch (Exception e ){
            e.printStackTrace();
        }finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
    
    
    /**
     * 查询美宜佳现有库存列表
     *
     * @param fileMeiyijiaInventory 美宜佳现有库存
     * @return 美宜佳现有库存
     */
    @Override
    public List<FileMeiyijiaInventory> selectFileMeiyijiaInventoryList(FileMeiyijiaInventory fileMeiyijiaInventory)
    {
        return fileMeiyijiaInventoryMapper.selectFileMeiyijiaInventoryList(fileMeiyijiaInventory);
    }
}